<template>
  <div class="search">
    <van-nav-bar
  title="搜索中心"
  left-arrow
  @click-left="$router.back()"
/>

<van-search
  v-model.trim="value"
  show-action
  shape="round"
  placeholder="请输入搜索关键词"
  @search="onSearch(value)"
  @input="onInput"
>
  <template #action>
    <div @click="onSearch(value)">搜索</div>
  </template>
</van-search>

   <!-- 推荐 -->
    <van-cell-group v-if="value">
      <van-cell  icon="search" v-for="(item, index) in sugList" :key="index"  @click="onSearch(item)">
        <span v-html="highLight(item, value)"></span>
      </van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"></van-cell>
      <van-cell  :title="item" v-for="item in history" :key="item"  @click="historySearch(item)">
        <van-icon @click.stop="del(item)" name="close" />
      </van-cell>
    </van-cell-group>

    <van-empty
    v-show="value && sugList.length===0"
  class="custom-image"
  image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
  description="暂无结果"
/>
  </div>
</template>

<script>
import { getSuggest } from '@/api/search'
import { setStroageSearchHistory, getStroageSearchHistory } from '@/utils/storage'
export default {
  name: 'Search',
  data() {
    return {
      value: '',
      // 推荐列表
      sugList: [],
      history: getStroageSearchHistory()
    }
  },
  methods: {
    // 高亮处理
    // 参数1：完整字符串
    // 参数2：高亮的关键字
    highLight (str, keyword) {
      const reg = new RegExp(keyword, 'gi')
      return str.replace(reg, item => {
        return `<span style="color: red;">${item}</span>`
      })
    },
    onInput() {
      clearTimeout(this.timerId)
      // 把开启的延时器的id记录到this.timerId上
      this.timerId = setTimeout(async () => {
        if (!this.value) return
        const res = await getSuggest(this.value)
        console.log('~ ~ res', res)
        // 空数据判断
        if (res.data.options[0] === null) {
          return (this.sugList = [])
        }
        this.sugList = res.data.options
      }, 500)
    },
    onSearch(item) {
      if (!item) {
        return this.$toast('请输入内容')
      }
      this.history = this.history.filter(val => val !== item)
      this.history.unshift(item)
      setStroageSearchHistory(this.history)
      this.$router.push({
        path: '/search/result',
        query: {
          keyword: item
        }
      })
    },
    del(item) {
      this.history = this.history.filter(val => val !== item)
    },
    historySearch(item) {
      this.keyword = item
      this.onSearch(this.keyword)
    }
  }

}
</script>

<style lang="less" scoped>
  .custom-image .van-empty__image {
    width: 60px;
    height: 60px;
  }
</style>
